<script setup>
import {ref,watch,onMounted} from 'vue'
import {getClazzList} from '@/api/clazz'
import {queryPageALLapi,saveStudent,deleteStudents,getStudentById,updateStudent,updatescoreById} from '@/api/stu'
import {ElMessage,ElMessageBox} from 'element-plus'

//初始化查询栏
const searchStu = ref({
  name: '',
  degree: '',
  clazzId: ''
})
//初始化班级列表
const clazzList = ref([])
//查询班级
const searchClazzList = async () => {
  const result = await getClazzList()
  if(result.code){
    clazzList.value = result.data
  }
}
//钩子函数
onMounted(()=>{
  searchClazzList()
  search()
})
//初始化学员列表
const studentList = ref([])
//查询学员
const search = async () => { 
  const result = await queryPageALLapi(searchStu.value.name,searchStu.value.degree,searchStu.value.clazzId,currentPage.value,pageSize.value)
  if(result.code){
    studentList.value = result.data.rows
    total.value = result.data.total
  }
}
//清空查询栏ku
const clear = () => {
  searchStu.value = {
    name: '',
    degree: '',
    clazzId: ''
  }
  search()
}
//分页条
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(false)
const total = ref(0)
//当页面改变时
const handleSizeChange = (val) => {
  search()
}
//当页码改变时
const handleCurrentChange = (val) => {
  search()
}
//控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
const studentFormRef = ref(null)
//初始化表单
const studentForm = ref({
  id: '',
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})
//设置表单验证
const rules = ref({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { max: 10, message: '长度为10个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { max: 18, message: '长度为18个字符', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ]
})
//新增打开表单
const addopStus = () => {
  if(studentFormRef.value){
    studentFormRef.value.resetFields()
  }
  dialogVisible.value = true
  dialogTitle.value = '新增学员'
  studentForm.value = {name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''}
}
//表单提交
const addStus = async () => { 
  if(!studentFormRef.value) return
  studentFormRef.value.validate(async (valid) => {
    if(valid){
      let result;
      if(studentForm.value.id){
        result = await updateStudent(studentForm.value)
      }else{
        result = await saveStudent(studentForm.value)
      }
      if(result.code){
        ElMessage.success('操作成功')
        dialogVisible.value = false
        search()
      }else{
        ElMessage.error('操作失败')
      }
    }else{
      ElMessage.error('表单校验不通过')
    }
  })
}
//定义选中的员工id
const selectedIds = ref([])
//多选框选中事件
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}
//批量删除学员
const deleteStus = () => {
  ElMessageBox.confirm('确定要删除吗？', '提示', 
  {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
  ).then(async () => {
    if (selectedIds.value && selectedIds.value.length > 0) {
      const result = await deleteStudents(selectedIds.value)
      if(result.code){ 
        ElMessage.success('删除员工成功')
        search()
      }else{
        ElMessage.error('删除员工失败')
      }
    } else {
      ElMessage.warning('请选择要删除的员工')
    }  
    }).catch(() => {
      ElMessage.info('已取消删除')
    }) 
}
//删除学员
const deleteStu = (ids) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', 
  {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}
  ).then(async () => {
      const result = await deleteStudents(ids)
      if(result.code){ 
        ElMessage.success('删除员工成功')
        search()
      }else{
        ElMessage.error('删除员工失败')
      }
    }).catch(() => {
      ElMessage.info('已取消删除')
    }) 
}
//修改学员的回显
const  getStuById = async (id) => {
  const result = await getStudentById(id)
  if(result.code){
    dialogVisible.value = true
    dialogTitle.value = '修改学员'
    studentForm.value = result.data
  }
}
//违纪表单
const dialogFormVisible = ref(false)
//定义违纪数据
const weijianForm = ref({
  id: null,
  score: null
})
//打开违纪表单
const addWeijian = async (id) => {
    dialogFormVisible.value = true
    weijianForm.value = {id: id,score: ''}
}
//修改违纪
const updateScore = async () => {
  const id = weijianForm.value.id
  const score = weijianForm.value.score

  if (!id || !score) {
    ElMessage.error('请填写完整信息')
    return
  }

  try {
    const result = await updatescoreById(id, score)
    if (result.code) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
      search()
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('更新评分出错:', error)
    ElMessage.error('网络异常，请重试')
  }
}
</script>

<template>
  <h1>学员管理</h1>
  <!-- 查询栏 -->
  <div class="search-container">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchStu.name" placeholder="请输入班级名称" clearable />
    </el-form-item>
    <el-form-item label="最高学历">
      <el-select
        v-model="searchStu.degree"
        placeholder="请选择"
        clearable
      >
        <el-option label="初中" value="1" />
        <el-option label="高中" value="2" />
        <el-option label="大专" value="3" />
        <el-option label="本科" value="4" />
        <el-option label="硕士" value="5" />
        <el-option label="博士" value="6" />
      </el-select>
    </el-form-item>
        <el-form-item label="所属班级">
      <el-select
        v-model="searchStu.clazzId"
        placeholder="请选择"
        clearable
      >
        <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查找</el-button>
      <el-button type="primary" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>
  <!-- 新增删除按钮 -->
  <div class="buttons">
  <span class="button"> <el-button type="primary" @click="addopStus" style="margin-right: 20px;">
    +新增员工
  </el-button></span>
  <span class="button"> <el-button type="danger" @click="deleteStus">
    -批量删除
  </el-button></span>
  </div>
  <!-- 表格 -->
   <div class="container">
      <el-table :data="studentList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center" @click="" />
    <el-table-column prop="name" label="姓名" width="100" align="center" />
    <el-table-column prop="no" label="学号" width="120" align="center" />
    <el-table-column prop="clazzName" label="班级" width="150" align="center" />
    <el-table-column prop="gender" label="性别" width="55" align="center">
      <template #default="scope">
        {{ scope.row.gender == "1" ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号"  width="120" align="center" />
    <el-table-column prop="degree" label="学历"  width="55" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree == 1">初中</span>
        <span v-else-if="scope.row.degree == 2">高中</span>
        <span v-else-if="scope.row.degree == 3">大专</span>
        <span v-else-if="scope.row.degree == 4">本科</span>
        <span v-else-if="scope.row.degree == 5">硕士</span>
        <span v-else-if="scope.row.degree == 6">博士</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数"  width="100" align="center" />
    <el-table-column prop="violationScore" label="违纪扣分"  width="100" align="center" />
    <el-table-column prop="updateTime" label="最后操作时间"  width="180" align="center" />
    <el-table-column label="操作"  align="center">
      <template #default="scoped">
        <el-button type="primary" size="small" @:click="getStuById(scoped.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
        <el-button type="warning" size="small" @:click="addWeijian(scoped.row.id)"><el-icon><WarningFilled /></el-icon>违纪</el-button>
        <el-button type="danger" size="small" @:click="deleteStu(scoped.row.id)"><el-icon><DeleteFilled /></el-icon>删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  </div>
  <!-- 表单 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="studentFormRef" :model="studentForm" :rules="rules" label-width="130px">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="studentForm.name"  placeholder="请输入姓名" style="width: 250px;" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="studentForm.no" placeholder="请输入学号" style="width: 250px;" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="studentForm.gender"
              placeholder="请选择"
              clearable
              style="width: 250px;" 
            >
        <el-option label="男" :value="1" />
        <el-option label="女" :value="2" />
      </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="studentForm.phone" placeholder="请输入手机号" style="width: 250px;" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="studentForm.idCard" placeholder="请输入身份证号" style="width: 250px;" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否有院校学员" prop="isCollege" >
            <el-select
              v-model="studentForm.isCollege"
              placeholder="请选择"
              clearable
              style="width: 250px;" 
            >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="studentForm.address" placeholder="请输入联系地址" style="width: 250px;" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select
              v-model="studentForm.degree"
              placeholder="请选择"
              clearable
              style="width: 250px;" 
            >
              <el-option label="初中" :value="1" />
              <el-option label="高中" :value="2" />
              <el-option label="大专" :value="3" />
              <el-option label="本科" :value="4" />
              <el-option label="硕士" :value="5" />
              <el-option label="博士" :value="6" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间" prop="username">
            <div class="block">
              <el-date-picker
                v-model="studentForm.graduationDate"
                type="date"
                placeholder="请选择毕业时间"
                :size="size"
                style="width: 250px;" 
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级" prop="name">
            <el-select
              v-model="studentForm.clazzId"
              placeholder="请选择"
              clearable
              style="width: 250px;" 
            >
              <el-option v-for="clazz in clazzList" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="addStus" style="margin-right: 50px;">
          保存
        </el-button>
        <el-button size="large" @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 分页条 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 40]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>
  <!-- 违纪处理表单 -->
   <div>
    <el-dialog v-model="dialogFormVisible" title="学员违纪处理" width="500" ref="weijianDialog">
      <el-form :model="weijianForm">
        <el-form-item label="违纪扣分" :label-width="formLabelWidth" style="margin-left: 50px;">
          <el-input v-model="weijianForm.score" autocomplete="off" align="center" style="width: 300px;" />
        </el-form-item>
      </el-form>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateScore">
          确认
        </el-button>
      </div>
    </template>
    </el-dialog>
   </div>
</template>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.search-container{
  margin: 20px 0 10px 100px;
}
.buttons{
  margin: 10px 0 10px 0;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin-top: 20px; /* 可根据需要调整间距 */
}
.dialog-footer{
  text-align: center;
}
</style>